<template>
  <div class="home">
    <el-container>
      <el-header height="auto">
        <el-row>
          <el-col :span="4" style="text-align:left;">
            <div class="head-left flex space-between" :style="{'width':isCollapse ? '65px' : '','padding-left':isCollapse ? '0' : ''}">
             <div class="head-title flex" v-if="!isCollapse">
                <img style="width: 52px;" src="@/assets/icon-logo.png" object-fit="contain" />
                <p>小宠悠悠</p>
             </div>
              <outdent :class="['navbar_outdent',isCollapse ? 'navbar-outdent-mini' : '']" :style="{'color':isCollapse ? '#fff' : ''}"></outdent>
            </div>
          </el-col>
          <el-col :span="20">
            <div class="navbar header-right">
              <!-- <full-screen style="float:right;" url="https://quan.fightingcat.net/full-screen.png" v-on:close="fullHandler"></full-screen> -->
              <div class="full_div">
                <el-image class="table-td-thumb" :src="require('../assets/fullscreen.png')" @click="fullHandler"></el-image>
              </div>
              <!-- <div style="width:20px;"></div> -->
              <div class="full_div">
                <el-image class="table-td-thumb" :src="require('../assets/help.png')" @click="helpHandler"></el-image>
              </div>
              <div style="width:10px;"></div>
              <el-dropdown style="float: right;" class="avatar-container right-menu-item hover-effect" trigger="click">
                <div class="avatar-wrapper flexRow">
                  <img :src="avatar" class="user-avatar" />
                  
                  <!-- <div style=""> -->
                  <p style="padding:0 10px;">{{ realName }}</p>
                  <i class="el-icon-caret-bottom" />
                  <!-- </div> -->
                </div>
                <el-dropdown-menu slot="dropdown" style="width:140px;">
                  <el-dropdown-item divided>
                    <span style="display:block;" @click="updatePwd"><i class="el-icon-edit-outline"></i> 修改密码</span>
                  </el-dropdown-item>
                  <el-dropdown-item divided>
                    <span style="display:block;" @click="logout"><i class="el-icon-warning-outline"></i> 退出登录</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <!-- <full-screen style="float:right;" url="https://quan.fightingcat.net/full-screen.png" v-on:close="fullHandler"></full-screen> -->
              <!-- <svg-icon icon-class="exit-fullscreen" /> -->
              <!-- <full-screen style="float:right;" :url="'require(../../assets/help.png)'" v-on:close="helpHandler"></full-screen> -->
            </div>
          </el-col>
        </el-row>
      </el-header>
      <el-container>
        <el-aside v-bind:style="aside_style">
          <el-menu :default-active="activeTab" class="el-menu-vertical-demo" :collapse-transition="false" background-color="#2c394b" text-color="#fff" @open="handleOpen" @close="handleClose" :collapse="isCollapse">
            <menu-tree v-for="item in permission_routes" :key="item.menuId" :menu="item" @func="clickMenu"></menu-tree>
          </el-menu>
        </el-aside>
        <el-main v-bind:style="main_style">
          <!-- <el-tabs v-model="editableTabsValue" type="card" editable @edit="handleTabsEdit">
          <el-tab-pane
            :key="item.name"
            v-for="(item, index) in editableTabs"
            :label="item.title"
            :name="item.name"
          >
            {{item.content}}
          </el-tab-pane>
        </el-tabs> -->
          <transition name="fade">
            <router-view></router-view>
            <!-- <el-tabs v-model="activeTab" closable @tab-remove="removeTab" @tab-click="handleClick">
              <el-tab-pane
                v-for="(item,index) in editableTabs"
                :data-url="item.menuUrl"
                :data-index="index"
                :key="item.menuId"
                :label="item.menuName"
                :name="`${ item.menuId }`"
              >
            <router-view v-if="activeTab == item.menuId"></router-view>
            </el-tab-pane>
          </el-tabs> -->
          </transition>
        </el-main>
      </el-container>
    </el-container>
    <pwd :dialog="pwdDialog" v-on:close="closePwdHandler"></pwd>
  </div>
</template>

<script>
// @ is an alias to /src
import {replaceUrlParam,accountMenusUrl,logoutUrl} from "@/utils/common";
import outdent from "../components/outdent/Outdents";
import fullScreen from "../components/full/index";
import MenuItem from "../components/Sidebar/MenuItem";
import MenuTree from "../components/Sidebar/MenuTree";
import Pwd from "./system/password";
import { mapState } from "vuex";

export default {
  name: "index",
  components: { fullScreen, outdent, MenuTree, Pwd },
 data() {
    return {
     activeTab:'',
      editableTabs: [],// tab标签
      aside_style: {
        width: "260px",
        backgroundColor: "background-color: red",
        height: document.documentElement.clientHeight - 92 + "px"
      },
      main_style: {
        height: document.documentElement.clientHeight - 92 + "px"
      },
      pwdDialog: false,
      // logo: null,
      avatar: require("@/assets/icon-logo.png"),
      realName: null,
      permission_routes: []
    };
  },
  computed: {
    ...mapState(['menuList','activeTabs']),
    isCollapse() {
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      this.aside_style.width = this.$store.state.isCollapse == true ? "65px" : "260px";
      return this.$store.state.isCollapse;
    }
  },
  watch:{
    "menuList":{
      handler(n,o){
          console.log(o)
        // 如果当前未有打开的窗口
        if(n.length <= 0){
          this.$router.push(this.initActiveTab().url);
          return
        }else{
          this.$router.push(this.activeTabs.url);
          
        }
        this.editableTabs = n
        
      },
      immediate:true
    },
    "activeTabs":{
      handler(n,o){
    
        this.activeTab = Object.keys(n).length > 0 ? `${ n.id }` : this.activeTab
        //this.activeTab = n.id
         if(n.url){
           console.log('页面',n)
          //  this.$router.push(n.url)
         }
      },
      immediate:true
    },
  },
  
  
  methods: {
   
   
    handleOpen(key, keyPath) {
      window.console.log(key, keyPath);
    },
    handleClose(key, keyPath) {
      window.console.log(key, keyPath);
    },
    logout() {
      let user = JSON.parse(sessionStorage.getItem("user"));

      this.axios.post(replaceUrlParam(logoutUrl,[user.id])).then(res => {
        sessionStorage.removeItem("user");

        this.$router.push("/login");
        console.log(res);
      });
    },
    loadMenus() {
      let user = JSON.parse(sessionStorage.getItem("user"));
      this.axios
        .post(replaceUrlParam(accountMenusUrl,[user.id]))
        .then(response => {
          if (response.data.status == "SUCCESS") {
            // this.menuDatas = response.data.data;
            let _data = response.data.data;
            this.permission_routes = response.data.data;
            // 如果当前没有选中的则设置默认
            console.log(_data)
            if(Object.keys(this.activeTabs).length <= 0){
              this.activeTab = `${ this.initActiveTab().id }`
              this.initTab()
              this.$router.push(this.initActiveTab().url);
              this.$store.commit('saveMenuList',this.editableTabs)
            }
            console.log("menus - ", this.permission_routes);
          } else {
            this.$message.success("菜单列表获取失败");
          }
        })
        .catch(response => {
          console.log("response -   " + response);
        });
    },
    /**
     * 初始化当前选中的tab
     */
    initActiveTab(){
      let _this = this
      let _data = _this.permission_routes
      console.log('初始化',_data)
      return {
        id:_data[0].children ? `${ _data[0].children[0].menuId }` : `${ _data[0].menuId }`,
        url:_data[0].children ? `${ _data[0].children[0].menuUrl }` : `${ _data[0].menuUrl }`,
        defaultData:_data[0].children ? _data[0].children[0] : _data[0]
      } 
    },
     /**
     * 初始化tab
     */
    initTab(){
      let _this = this
      _this.$store.commit('saveActiveTab',{id:`${ _this.initActiveTab().id }`,url:_this.initActiveTab().url})
      _this.editableTabs.push(_this.initActiveTab().defaultData)
      console.log('editableTabs',_this.initActiveTab().defaultData)
      
    },

    /**
     * 修改密码
     */
    updatePwd(){
      this.pwdDialog = true;
    },
    closePwdHandler(){
      this.pwdDialog = false;
    },
    helpHandler () {
      window.open("http://test.manage.easycarlife.cn/easyhelp/sub/2021-05-20.html");
    },
    fullHandler() {
      let element = document.documentElement;
      if (element.requestFullscreen) {
        element.requestFullscreen();
      } else if (element.webkitRequestFullScreen) {
        element.webkitRequestFullScreen();
      } else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen();
      } else if (element.msRequestFullscreen) {
        // IE11
        element.msRequestFullscreen();
      }
    },
    /**
     * tab标签删除按钮
     */ 
    removeTab(targetName, action) {
      let _this = this
      let tabs = this.editableTabs;
      let activeIndex;
                console.log(action)

      // if(_this.activeTab == targetName){
      tabs.forEach((item,index) => {
        if(`${ item.menuId }` == targetName){
          console.log(item.menuId,index)
          
          // 判断当前删除后是展示后面的还是前面的
          if(index == 0){
            activeIndex = _this.editableTabs.length > 1 ? (index + 1) : 0
          }else{
            activeIndex = (index - 1) >= 1 ? (index - 1) : 0
          }
         console.log('activeIndex',activeIndex)
         // 判断当前卡片是否是最后一个
         let flag = _this.editableTabs.length <=1;
          _this.activeTab = flag ? `${ _this.initActiveTab().id }` : `${ _this.editableTabs[activeIndex].menuId }`
          let menuUrl = flag ? _this.initActiveTab().url : _this.editableTabs[activeIndex].menuUrl
          _this.editableTabs.splice(index,1)
          

          // 如果是最后一个则默认显示第一个
          if(flag){
            _this.initTab()
          }
          
          _this.$store.commit('saveMenuList',this.editableTabs)
          _this.$router.push(menuUrl)
        }
      })
      console.log('activeTab',_this.activeTab)
      console.log('当前索引',activeIndex,_this.editableTabs[activeIndex].menuUrl)
      // this.editableTabs = tabs.map(tab => `${ tab.menuId }` != targetName);
      
      // }
     



    },
    clickMenu() {

      this.editableTabs = JSON.parse(sessionStorage.getItem("saveActiveTab"));
      
       this.$router.push(this.editableTabs.url)
    },
    handleClick(tab,e) {
      // this.activeName=tab.name;
      let _this = this;
     
      let routeUrl = _this.$router.currentRoute.fullPath;
      let currentUrl = tab.$attrs['data-url'];
      if(routeUrl == currentUrl){
        return
      }
       _this.$router.push(tab.$attrs['data-url'])
       _this.$store.commit('saveActiveTab',{id:`${ tab.name }`,url:currentUrl})

    }
  },
  mounted() {
    let _this = this;
    
    window.onresize = function () {
      _this.$store.state.screenHeight = document.documentElement.clientHeight; //窗口高度
      _this.main_style.height = _this.$store.state.screenHeight - 60 + 'px';
      _this.aside_style.height = _this.$store.state.screenHeight - 60 + 'px';
    };
    // this.$router.push(this.editableTabs.url)

    var user = JSON.parse(sessionStorage.getItem("user"));
    this.realName = user.realName;
    this.loadMenus();
  },
};
</script>
<style lang="less">
.el-dropdown-menu{
  padding: 0;
  li{
    &:first-child{
      border-top: none;
    }
  }
}
.el-header {
  background-color: #ffffff;
  color: #333;
  text-align: center;
  padding: 0;
  /* line-height: 60px; */
  /* padding: 0%; */
  .head-left{
      background-color: #2c394b;
      width: 260px;
      height: 92px;
      padding: 0 12px;
      box-sizing: border-box;
      
    p{
      font-size: 24px;
      padding-left: 10px;
      color: #F5CB4C;
      text-shadow: #000 1px 0 0, #000 0 1px 0, #000 -1px 0 0, #000 0 -1px 0;

    }
  }
  .navbar_outdent {
    position: absolute;
    left: 260px;
    cursor: pointer;
    &:hover{
      background-color: transparent;
    }
    &.navbar-outdent-mini{
      position: static;
    }
  }
}

.el-aside {
  background-color: #2c394b;
  color: #333;
  text-align: left;
  transition: All .3s;
  // width: 261px!important;
  .el-menu{
    width: 260px!important;
    .el-menu-item{
      &.is-active{
        background-color: #495f7c;
      }

    }
  }
}

.el-main {
  background-color: #fff;
  color: #333;
  text-align: center;
  padding:0 50px 0 50px;
  /* padding: 10px; */
}
.el-tabs__nav-wrap{
  // padding: 10px;
  background-color: #fff!important;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.el-row {
  // margin-bottom: 20px;
  background-color: #ffffff;
  // height: 60px;
}
.el-col {
  border-radius: 4px;
}
.el-tabs__content{
  // margin-top: 100px;
}
#outdeng_div {
  display: inline;
}
.table-head-box{
  padding-bottom: 30px;
  .el-input{
    width: 300px;
    margin-right: 20px;
  }
}
.el-dialog__body{
  .el-select{
  width: 100%;
  .el-input{
    width: 100%;
  }
}
}
.el-pagination{
  margin-top: 30px;
}
</style>
<style lang="less" scoped>

.navbar {
 

  
}
.avatar-container {
  margin-right: 30px;
  // margin-top: 5px;
  height: 60px;

  .avatar-wrapper {
    margin-top: 8px;
    justify-content: center;
    // position: relative;

    .user-avatar {
      cursor: pointer;
      width: 34px;
      height: 34px;
      border-radius: 20px;
      display: inline-block;
    }

    .el-icon-caret-bottom {
      cursor: pointer;
      // position: absolute;
      // right: -20px;
      // top: 25px;
      font-size: 12px;
    }
  }
}
.full_div {
  width: 50px;
  height: 60px;
  display: flex;
  vertical-align: middle;
  align-items: center;
  justify-content: center;
}
.full_div:hover {
  background-color: lightgray;
}
.full_div:active {
  background-color: lavenderblush;
}
.table-td-thumb{
  width: 28px;
  height: 28px;
}
.header-right{
  display: flex;
  justify-content: right;
  align-items: center;
  height: 92px;
}

</style>
